<template>
  <div>
    <div class="mainor_form">
      <el-form
        :inline="true"
        :model="form"
        class="demo-form-inline"
        ref="userListFrom"
        label-width="100px"
        id="form"
      >
        <el-form-item prop="date_type">
          <el-select
            class="selectBox"
            v-model="form.date_type"
            placeholder="请选择"
          >
            <el-option label="配送日期" value="1"> </el-option>
            <el-option label="下单日期" value="2"> </el-option>
          </el-select>
          <el-date-picker
            v-model="establishTime"
            type="daterange"
            class="time220"
            style="margin-left: -4px"
            :editable="false"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :clearable="false"
            :picker-options="pickerOptions"
            @change="dateChange"
          />
        </el-form-item>
        <el-form-item label="用户名称：" prop="uid">
          <change-user-input
            ref="changeUserInput"
            @sendValue="getUser"
            @clear="clearUid"
          ></change-user-input>
        </el-form-item>
        <el-form-item label="商品名称：" prop="goods_spu_id">
          <change-goods-input
            ref="changeGoodsInput"
            @clear="
              () => {
                this.form.goods_spu_id = '';
              }
            "
            @sendValue="
              (data) => {
                this.form.goods_spu_id = data.id;
              }
            "
          ></change-goods-input>
        </el-form-item>
        <MainFormBtn @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="moredata">
          <el-button @click="exportform">导出</el-button>
        </MainFormBtn>
        <div class="more el-form-item" @click="moredata = !moredata">
          <span>更多</span>
          <i :class="[{ on: moredata }, ' el-icon-arrow-down']"></i>
        </div>
        <div class="clearfix"></div>
        <el-collapse-transition>
          <div v-show="moredata">
            <el-form-item label="子账户：" prop="sub_zid">
              <el-select
                v-model.trim="form.zid"
                placeholder="子账户"
                class="wid220"
                filterable
              >
                <el-option
                  v-for="(subAccount, index) in address.subAccount"
                  :key="index"
                  :label="subAccount.nickname"
                  :value="subAccount.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品分类：" prop="category_id">
              <el-cascader
                style="width: 220px"
                v-model="form.category_id"
                :options="options"
                :props="defaultProps"
              ></el-cascader>
            </el-form-item>
            <div class="clearfix"></div>
            <el-form-item label=" ">
              <MainFormBtn class="btn-bottom" @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="!moredata">
                <el-button @click="exportform">导出</el-button>
              </MainFormBtn>
            </el-form-item>
          </div>
        </el-collapse-transition>
      </el-form>
    </div>
    <div class="main_table">
      <el-table
      ref="multipleTable"
      class="mg-t-4"
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中"
      fit
      highlight-current-row
      :header-cell-class-name="this.$verticaline"
      :height="borderHeight"
      :header-cell-style="tableHeightStyle"
    >
      <el-table-column label="商品名称" prop="goods_name">
        <template slot-scope="scope">{{ scope.row.goods_name }}</template>
      </el-table-column>
      <el-table-column label="单位" prop="unit" />
      <el-table-column label="SKU编码" prop="goods_spu_code" />
      <el-table-column label="配送数量" prop="sort_num" />
      <el-table-column label="配送均价" prop="send_avg_price" />
      <el-table-column label="配送金额" prop="send_money">
        <template slot-scope="scope">
          {{ scope.row.send_money | twoPlace }}
        </template>
      </el-table-column>
      <el-table-column label="退货金额" prop="return_money">
        <template slot-scope="scope">
          {{ scope.row.return_money | twoPlace }}
        </template>
      </el-table-column>
      <el-table-column label="成本金额" prop="cost">
        <template slot-scope="scope">
          {{ scope.row.cost | twoPlace }}
        </template>
      </el-table-column>
      <el-table-column label="利润金额" prop="profit">
        <template slot="header">
          <headerSortArrow
            label="profit"
            ref="arrow1"
            @handleSort="handleSort($event, 'arrow1')"
            >利润金额</headerSortArrow
          >
        </template>
        <template slot-scope="scope">
          {{ scope.row.profit | twoPlace }}
        </template>
      </el-table-column>
      <el-table-column label="利润率" prop="profit_rate">
        <template slot="header">
          <headerSortArrow
            label="profit_rate"
            ref="arrow2"
            @handleSort="handleSort($event, 'arrow2')"
            >利润率</headerSortArrow
          >
        </template>
        <template slot-scope="scope"> {{ scope.row.profit_rate }}% </template>
      </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="flex-row-end marginTop10">
      <MainPagination
        :current-page="current.page"
        :page-sizes="[20, 30, 50, 100]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        background
        @size-change="changeLimit"
        @current-change="changePage"
      />
    </div>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import { get_profitGoods, export_exportProfitGoods } from "@/api/report/index";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { report_shortcuts } from "@/options/new_dateOption";
import { parseTime, exportMethod, getNowMonth } from "@/utils/index";
import { recursion, category } from "@/utils/index";
import headerSortArrow from "@/views/report/components/headerSortArrow";
import { user_getMemberInfo } from "@/api/currency";

export default {
  mixins: [mixins],
  components: { headerSortArrow },
  data() {
    return {
      pickerOptions: report_shortcuts,
      getNowMonth,
      // 时间
      parseTime,
      exportMethod,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 列表数据
      list: [],
      // 分类
      options: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
        value: "id",
        checkStrictly: true,
      },
      listLoading: false,
      // 搜索
      form: {
        start_time: "",
        end_time: "",
        uid: "",
        pid: "",
        category_id: [],
        date_type: "1",
        order_by: "",
        order_type: "", //1升序  2降序
        zid: "",
        sub_zid: null,
      },
      //   establishTime: ["2020-09-01", "2020-12-31"],
      establishTime: [],
      moredata: false,
      address: {
        subAccount: [],
      },
    };
  },
  created() {
    this.getNumerical(325);
    // 列表
    this.establishTime = this.getNowMonth();
    let show = Object.hasOwn(this.$route.query, "name");
    if (show) {
      this.form.date_type = this.$route.query.type;
      this.establishTime = this.$route.query.time;
      this.$nextTick(() => {
        this.$refs.changeUserInput.name = this.$route.query.name;
        this.$set(this.form, "uid", this.$route.query.uid);
      });
    }
    this.$nextTick(() => {
      this.get_profitGoods();
    });
  },
  methods: {
    startGetting() {
      this.getSearchFor();
    },
    // 搜索并折叠搜索条件
    getSearchFor() {
      this.getArticleList();
    },
    // 获取用户
    getUser(data) {
      let uid = data.info.user_id;
      this.form.uid = uid;
      this.user_getMemberInfo(uid);
    },
    //获取子账号
    user_getMemberInfo(uid) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: uid }
      );
      user_getMemberInfo(data).then((res) => {
        if (res.errcode == 0) {
          res.data.subAccount.map((e, ind) => {
            if (ind == 0) {
              e.id = 0;
              e.nickname = "主账号";
            }
          });
          res.data.subAccount.unshift({
            id: "",
            nickname: "所有",
          });
          this.address = res.data;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    //选择子账号事件
    // sub_account(val) {
    //   this.form.zid = this.address.subAccount[val].id;
    // },
    // 清除用户的uid
    clearUid() {
      this.form.uid = "";
      this.address.subAccount = [];
      this.form.sub_zid = "";
      this.form.zid = "";
    },
    get_profitGoods() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      get_profitGoods(data).then((res) => {
        if (res.errcode == 0) {
          this.options = recursion(res.data.category_list, true);
          this.list = res.data.list;
          this.totalCount = res.data.total;
        } else {
          this.$message.error(res.errmsg);
        }
        this.listLoading = false;
      });
    },
    // 重置
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.establishTime = this.getNowMonth();
      if (this.moredata) {
        this.$refs["changeUserInput"].name = "";
        this.$refs["changeGoodsInput"].name = "";
        this.form.zid = "";
      }
      this.get_profitGoods();
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.get_profitGoods();
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.get_profitGoods();
    },
    changePage(page) {
      this.current.page = page;
      this.get_profitGoods();
    },

    list_form() {
      let { sub_zid, ...form } = JSON.parse(JSON.stringify(this.form));
      // form.zid = form.zid ? form.zid : 0;
      form.start_time = this.establishTime[0] ? this.establishTime[0] : "";
      form.end_time = this.establishTime[1] ? this.establishTime[1] : "";
      form.pid = form.category_id[0] ? form.category_id[0] : "";
      form.category_id = category(form.category_id);
      return form;
    },
    // 排序
    handleSort(data, ref) {
      let arr = ["arrow1", "arrow2"].filter((e) => e != ref);
      arr.map((e) => {
        this.$refs[e].selected = false;
      });
      this.form.order_by = data.label;
      this.form.order_type = data.type;
      this.get_profitGoods();
    },
    // 导出
    exportform() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form()
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_exportProfitGoods(data).then((res) => {
        this.exportMethod(res, "利润报表-商品", notify);
      });
    },
    // 日期选择
    dateChange(val) {
      let start = new Date(val[0]).getTime();
      let end = new Date(val[1]).getTime();
      let diff = start - end;
      if (Math.abs(diff) > 3600 * 1000 * 24 * 60) {
        this.$message.warning("选择时间跨度不能超过两个月");
        this.establishTime = this.getNowMonth();
      }
      this.get_profitGoods();
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.container {
  background-color: #fff;
  padding: 10px;
}
.mainsu {
  .mainor_form form {
    width: 100%;
  }
}

// 支付状态
.success {
  color: $green;
}
.unpaid {
  color: $colour_red;
}
// 订单状态
.order0 {
  color: $order_color1;
}
.order1 {
  color: $order_color2;
}
.order2 {
  color: $order_color3;
}
.order4 {
  color: $order_color4;
}
.selectBox {
  width: 100px;

  /deep/.el-input__inner {
    border: none;
    width: 100px !important;
  }
}
/deep/.mainor_form form .el-form-item {
  margin-bottom: 10px;
  &:last-child {
    margin-bottom: 6px;
  }
}
</style>
